package civicinity.ist.psu.edu;

import java.io.File;
import java.util.Timer;
import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.events.CivicinityEventParticipate;
import civicinity.ist.psu.edu.share.CivicinityMyView;
import civicinity.ist.psu.edu.utils.CivicinityCameraMode;
import civicinity.ist.psu.edu.utils.MyLocation;
import civicinity.ist.psu.edu.utils.MyLocation.LocationResult;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class CivicinityActivity extends Activity {
    /** Called when the activity is first created. */

	private SharedPreferences mPref;
	private LocationManager mManager;
	private double mLatitude = 0.0;
	private double mLongitude = 0.0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        MyLocation myLocation = new MyLocation();
	    myLocation.getLocation(this, locationResult);
        
        File file = new File(Constants.CIVICINITY_ROOT_PATH);
		if(!file.exists()) {
			file.mkdir();
		}
		
		file = new File(Constants.CIVICINITY_FILE_PATH);
		if(!file.exists()) {
			file.mkdir();
		}
		
		mPref = PreferenceManager.getDefaultSharedPreferences(this);
		
        // set up LocationManager
        mManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		// check if GPS is on.
		checkGpsIsOn();
		
    }
    
	public LocationResult locationResult = new LocationResult() {

		@Override
		public void gotLocation(Location location) {
			// TODO Auto-generated method stub
			mLatitude = location.getLatitude();
			mLongitude = location.getLongitude();
			
			/**
    	     * Start service whenever app starts
    	     */
	        SharedPreferences.Editor editor = mPref.edit();
			editor.putString("latitude", String.valueOf(mLatitude));
			editor.putString("longitude", String.valueOf(mLongitude));	        
			editor.commit();
		}
	};

	private void startActivity() {
		// check if GPS data is stored.
        if(Double.parseDouble(mPref.getString("latitude", "0.0")) == 0.0
        		|| Double.parseDouble(mPref.getString("longitude", "0.0")) == 0.0) {
        	
        	new getInitialGeoPoint().execute();
        }
        else {
            if(!mPref.getBoolean("loggedin", false)) {
            	startActivity(new Intent(this, CivicinityLogin.class));
            	finish();
            }
            else {
            	startActivity(new Intent(this, CivicinityMainpage.class));
            	finish();
            }
        }
	}
	
    public void checkGpsIsOn() {
		// check if GPS is turned on...
		if (mManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			startActivity();
		}
		else {

		 new AlertDialog.Builder(CivicinityActivity.this)
		   		.setTitle("Turn On GPS")
		   		.setMessage("Your location service is disabled. Please enable both 'Use Wireless Networks' and 'Use GPS Satellites'. " +
		   				"Would you like to go to the Location&security settings page?")
		   		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		   			public void onClick(DialogInterface dialog, int whichButton) {
		   				Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
		   				startActivityForResult(intent, 1);
		   			}
		   		})
		   		.setNegativeButton("No", new DialogInterface.OnClickListener() {
		   			public void onClick(DialogInterface dialog, int whichButton) {
		   				finish();
		   			}
		   		})
		   		.show();
		}	
	}
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    	if (requestCode == 1) {
			startActivity();
		}
	}

    
    private final LocationListener mGPSLocationListener = new LocationListener() {

		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			
			Log.i("K", "latitude : " + location.getLatitude() + " longitude : " + location.getLongitude() + " accuracy : " + location.getAccuracy());
			
			mLatitude = location.getLatitude();
			mLongitude = location.getLongitude();
			
			mManager.removeUpdates(mGPSLocationListener);
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
		
	};
    
	private class getInitialGeoPoint extends AsyncTask<Void, Void, Void> {
		
		private ProgressDialog mGPSDialog;
		
		@Override
	    protected void onPreExecute() {
	    	
	    	mManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mGPSLocationListener);
	    	
	    	mGPSDialog = new ProgressDialog(CivicinityActivity.this);
	    	mGPSDialog.setTitle("Getting Your Location");
	    	mGPSDialog.setMessage("Please wait while finding your location...");
	    	mGPSDialog.setCancelable(true);
	    	mGPSDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface arg0) {
					// TODO Auto-generated method stub
					mGPSDialog.dismiss();
					Toast.makeText(CivicinityActivity.this, "Cancelled by the user.", Toast.LENGTH_SHORT).show();
					finish();
				}
	    	});
	    	mGPSDialog.show();
	    }
		
		
		
	    /** The system calls this to perform work in a worker thread and
	      * delivers it the parameters given to AsyncTask.execute() */
		@Override
	    protected Void doInBackground(Void... Void) {
	    	
	    	while(true) {
	    		if(mLatitude != 0.0 && mLongitude != 0.0) {
	    			
	    			Log.i("K", "Get GPS data!");
	    			
	    			return null;
	    		}
	    	}
	    }
	    
	    /** The system calls this to perform work in the UI thread and delivers
	      * the result from doInBackground() */
	    @Override
	    protected void onPostExecute(Void unused) {
	    	
	    	Log.i("K", "In PostExecute()");
	    	
	    	if(mGPSDialog.isShowing()) {
	    		mGPSDialog.dismiss();
	    	}
	        
            if(!mPref.getBoolean("loggedin", false)) {
            	startActivity(new Intent(CivicinityActivity.this, CivicinityLogin.class));
            	finish();
            }
            else {
            	startActivity(new Intent(CivicinityActivity.this, CivicinityMainpage.class));
            	finish();
            }
    	    
    	    /**
    	     * Start service whenever app starts
    	     */
	        SharedPreferences.Editor editor = mPref.edit();
			editor.putString("latitude", String.valueOf(mLatitude));
			editor.putString("longitude", String.valueOf(mLongitude));	        
			editor.commit();
	    }
	}
}